//
//  ViewController.m
//  webViewTest
//
//  Created by luyue on 14/11/5.
//  Copyright (c) 2014年 Luyue. All rights reserved.
//

#import "ViewController.h"
#import "CustomNumbleKeyboardView.h"

#define URLSTRING @"https://www.baidu.com"
#define JSFIELDNAME @"field_3"

#define IOS7_OR_LATER   ( [[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending )

@interface ViewController ()<UIWebViewDelegate,CustomNumberKeyBoardDelegate,UIScrollViewDelegate>
@property (strong, nonatomic) IBOutlet UIWebView *webv;
@property (strong, nonatomic) CustomNumbleKeyboardView *customKeyboard;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *webViewTopSpace;

@end

@implementation ViewController
// UIKeyboardWillShowNotification和UIKeyboardWillHideNotification为键盘弹出或移除时iOS系统post notification的名字，这里只需要定义self为这个通知的接收者即可。
// viewWillAppear:和viewWillDisappear:大家应该都很清楚，这两个方法分别在self loadView和removefromsuperview后执行。
// 特别注意：这里的object参数需要是nil,不然取不到键盘的userInfo
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue* value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue]; // 这里得到了键盘的frame
    // 你的操作，如键盘出现，控制视图上移等
}

- (void)keyboardWillHide:(NSNotification *)notification {
    // 获取info同上面的方法
    // 你的操作，如键盘移除，控制视图还原等
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
    if ( IOS7_OR_LATER )
    {
        self.webViewTopSpace.constant = 20;
    }
#endif
    
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    self.customKeyboard = [[CustomNumbleKeyboardView alloc] initWithFrame:(CGRect){0, screenBounds.size.height, screenBounds.size.width, 0}];
    self.customKeyboard.cdelegate = self;
    
    self.webv.keyboardDisplayRequiresUserAction = NO;
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    [self.webv loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: path]]];
    self.webv.scrollView.delegate = self;
    
    
//    NSURL *url = [NSURL URLWithString:URLSTRING];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    [self.webv loadRequest:request];
}

- (void)keyboardWillShowOrHide:(NSNotification*)notif
{
//    if (![@"true" isEqualToString : self.settings[@"KeyboardShrinksView"]]) {
//        return;
//    }
    BOOL showEvent = [notif.name isEqualToString:UIKeyboardWillShowNotification];
    
    CGRect keyboardFrame = [notif.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardFrame = [self.view convertRect:keyboardFrame fromView:nil];
    
    CGRect newFrame = self.view.bounds;
    if (showEvent) {
        newFrame.size.height -= keyboardFrame.size.height;
    }
    self.webv.frame = newFrame;
    self.webv.scrollView.contentInset = UIEdgeInsetsMake(0, 0, -keyboardFrame.size.height, 0);
}
//响应数字输入
- (void) numberKeyBoardInput:(NSInteger) number
{
    [self creatJavaScriptStringWith:[NSString stringWithFormat:@"%ld",(long)number]];
}
//响应空格输入
- (void) numberKeyBoardBackspace
{
    NSString *valueString = [self.webv stringByEvaluatingJavaScriptFromString:@"var field = document.getElementById('field_3');""field.value"];
    if (valueString.length > 0) {
        valueString = [valueString substringToIndex:valueString.length-1];
    }else{
        valueString = @"";
    }
    NSString *jsString = [NSString stringWithFormat:@"var field = document.getElementById('%@');""field.value='%@';",JSFIELDNAME,valueString];
    [self.webv stringByEvaluatingJavaScriptFromString:jsString];
}
//响应完成按键输入
- (void) numberKeyBoardFinish
{
    [self hiddenCustomKeyboard];
}
-(void)creatJavaScriptStringWith:(NSString *)inputString
{
    NSString *valueString = [self.webv stringByEvaluatingJavaScriptFromString:@"var field = document.getElementById('field_3');""field.value"];
    NSString *tempString = inputString;
    if (valueString) {
        tempString = [valueString stringByAppendingString:inputString];
    }
    NSString *jsString = [NSString stringWithFormat:@"var field = document.getElementById('%@');""field.value='%@';",JSFIELDNAME,tempString];
    [self.webv stringByEvaluatingJavaScriptFromString:jsString];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self hiddenCustomKeyboard];
}
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *s = request.mainDocumentURL.relativePath;
    if ( [request.mainDocumentURL.relativePath isEqualToString:@"/clicked"] ) {        //the image is clicked, variable click is true
        NSLog( @"image clicked" );
        UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"JavaScript called"
                                                     message:@"You’ve called iPhone provided control from javascript!!" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        [alert show];
        return false;
    }
    if ( [request.mainDocumentURL.relativePath isEqualToString:@"/jumpKeyboard"] ) {        //the image is clicked, variable click is true
        
        [self tapAddButton];
        return false;
    }
    return true;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"title11=%@",title);
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"title=%@",title);
   
    //添加数据
    [self.webv stringByEvaluatingJavaScriptFromString:@"var field = document.getElementById('field_2');""field.value='Multiple statements - OK';"];
    //[myWebView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
    //     "script.type = 'text/javascript';"
    //     "script.text = \"function myFunction() { "
    //     "var field = document.getElementById('field_3');"
    //     "field.value='Calling function - OK';"
    //     "}\";"
    //     "document.getElementsByTagName('head')[0].appendChild(script);"];
    //
    //    [myWebView stringByEvaluatingJavaScriptFromString:@"myFunction();"];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
    [button addTarget:self action:@selector(tapAddButton) forControlEvents:UIControlEventTouchUpInside];
    button.center = self.view.center;
    [self.view addSubview:button];
    
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{ 
}

-(void)tapAddButton
{
    [self.customKeyboard showCustomKeyboard];
}
-(void)hiddenCustomKeyboard
{
    [self.customKeyboard dismissCustomKeyboard];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
